import { useEffect } from 'react';
import { uPlc, useTimer } from 'sui';
import { do_step } from 'step/scan';
import { g_line, g_db } from 'db/state';

let g_block = false;

const isblock = () => g_block;
const block = () => g_block = true;
const unblock = () => g_block = false;

const watch = {
    startWatch: () => unblock(),
    stopWatch: () => block()
};

const reducer = (wsn, umd) => {
    if (g_db.is_stop_scan()) {
        return;
    }

    if (isblock()) {
        return;
    }

    block();

    uPlc(null, "get",
        {
            line: g_line(),
            sn: wsn,
        },
        r => {
            do_step(r, umd, watch);
        },
        e => {
            do_step(null, umd, watch);
        }
    );
};

const useScan = (wsn, umd) => {
    useEffect(() => {
        unblock();
    }, []);

    const action = (state, action) => {
        if (action.type === "update") {
            reducer(wsn, umd);
        }

        return state;
    }

    useTimer(action, 400);
};

export {useScan};
